﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using CivilRegistry.Common;
using CivilRegistry.ControlledModel;

namespace CivilRegistry
{
    public partial class BirthCertificate : System.Web.UI.Page
    {
        Admin loggedInAdmin = null;
        Person loggedInPerson = null;
        bool isApproved;
        bool isDeactivated;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (SessionHandler.CurrentSession.User == null)
            {
                Response.Redirect("~/Login.aspx?&redirect=BirthCertificate.aspx");
            }

            SiteMaster masterPage = (SiteMaster)Page.Master;
            masterPage.SelectedMenu = "BirthCertificate";

            lblStatus.Text = "";

            if (SessionHandler.CurrentSession.User is Admin)
            {
                this.loggedInAdmin = (Admin)SessionHandler.CurrentSession.User;
            }
            else if (SessionHandler.CurrentSession.User is Person)
            {
                this.loggedInPerson = (Person)SessionHandler.CurrentSession.User;
            }
            else
            {
                Response.Redirect("~/Default.aspx");
            }

            if (!Page.IsPostBack)
            {
                if (SessionHandler.CurrentSession.User is Admin)
                {
                    pnlDisplay.Visible = false;
                    pnlAdmin.Visible = true;
                }
                else
                {
                    this.LoadBirthCertificateValues(ControlledModel.BirthCertificate.FindByPerson(this.loggedInPerson));
                    pnlAdmin.Visible = false;
                }
            }
        }

        private void FillBirthCertificateGrid()
        {
            this.FillBirthCertificateGrid("BirthCertificateId", SortDirection.Ascending);
        }

        private void FillBirthCertificateGrid(string columnName, SortDirection sortDirection)
        {
            int pageIndex = gvBirthCertificate.PageIndex;
            if (pnlFilter.Visible)
            {
                gvBirthCertificate.DataSource = this.loggedInAdmin.GetBirthCertificatesBy(cblFilter.Items[0].Selected, cblFilter.Items[1].Selected).OrderBy(columnName, sortDirection);
            }
            else
            {
                gvBirthCertificate.DataSource = this.loggedInAdmin.GetBirthCertificatesForApproval().OrderBy(columnName, sortDirection);
            }
            gvBirthCertificate.DataBind();
            gvBirthCertificate.PageIndex = pageIndex;
        }

        protected void gvBirthCertificate_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (SessionHandler.CurrentSession.SortDirection == SortDirection.Descending)
            {
                SessionHandler.CurrentSession.SortDirection = SortDirection.Ascending;
            }
            else
            {
                SessionHandler.CurrentSession.SortDirection = SortDirection.Descending;
            }

            this.FillBirthCertificateGrid(e.SortExpression, SessionHandler.CurrentSession.SortDirection);
            
        }

        protected void gvBirthCertificate_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvBirthCertificate.PageIndex = e.NewPageIndex;
            this.FillBirthCertificateGrid();
        }

        protected void gvBirthCertificate_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Edit")
            {
                var hdnBirthCertificateId = (HiddenField)gvBirthCertificate.Rows[Convert.ToInt32(e.CommandArgument) - (gvBirthCertificate.PageSize * gvBirthCertificate.PageIndex)].FindControl("hdnBirthCertificateId");

                this.LoadBirthCertificateValues(ControlledModel.BirthCertificate.FindById(Convert.ToInt32(hdnBirthCertificateId.Value)));

                gvBirthCertificate.Visible = false;
                pnlFilter.Visible = false;
                btnApply.Visible = false;
                pnlTools.Visible = false;
                pnlDisplay.Visible = true;
                pnlAdminActions.Visible = true;

                if (this.isApproved)
                {
                    btnApprove.Visible = false;
                    btnDeny.Visible = false;
                    btnDeactivate.Visible = true;
                    if (this.isDeactivated)
                    {
                        btnDeactivate.Text = "Re-Activate";
                    }
                    else
                    {
                        btnDeactivate.Text = "Deactivate";
                    }
                }
                else
                {
                    btnApprove.Visible = true;
                    btnDeny.Visible = true;
                    btnDeactivate.Visible = false;
                }
            }
        }

        protected void gvBirthCertificate_RowEditing(object sender, GridViewEditEventArgs e)
        {
            e.Cancel = true;
        }

        private void LoadBirthCertificateValues(ControlledModel.BirthCertificate objBirthCertificate)
        {
            if (objBirthCertificate != null)
            {
                this.isApproved = objBirthCertificate.IsApproved != null ? objBirthCertificate.IsApproved.Value : false;
                this.isDeactivated = objBirthCertificate.DeactivateReason == null ? false : true;
                hdnBirthCertificateId.Value = objBirthCertificate.BirthCertificateId.ToString();
                lblFirstNameValue.Text = objBirthCertificate.ChildFirshtName;
                lblMiddleNameValue.Text = objBirthCertificate.ChildMiddleName;
                lblLastNameValue.Text = objBirthCertificate.ChildLastName;
                lblDateOfBirthValue.Text = Convert.ToString(objBirthCertificate.BirthReport.DateOfBirthOftheChild);

                string genderOftheChild = null;

                if (objBirthCertificate.BirthReport.GenderOftheChild == "M")
                {
                    genderOftheChild = "Male";
                }
                else if (objBirthCertificate.BirthReport.GenderOftheChild == "F")
                {
                    genderOftheChild = "Female";
                }

                lblGenderValue.Text = genderOftheChild;
                lblCivilHospitalValue.Text = objBirthCertificate.BirthReport.CivilHospital.FirstName;               
            }
            else
            {
                lblStatus.Text = "No Birth Certificate found for you account. Please contact the relavant office for more information.";
                pnlDisplay.Visible = false;
            }
        }

        protected void btnApply_Click(object sender, EventArgs e)
        {
            pnlDisplay.Visible = false;
            pnlBirthCertificateRequest.Visible = true;
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            ControlledModel.BirthCertificate objBirthCertificate = new ControlledModel.BirthCertificate();

            objBirthCertificate.ChildFirshtName = txtFirstName.Text;
            objBirthCertificate.ChildMiddleName = txtMiddleName.Text;
            objBirthCertificate.ChildLastName = txtLastName.Text;

            Relation relationWithChild = 0;

            switch (rblRelation.SelectedValue)
            {
                case "F":
                    relationWithChild = Relation.Father;
                    break;
                case "M":
                    relationWithChild = Relation.Mother;
                    break;
                case "G":
                    relationWithChild = Relation.Gaurdian;
                    break;
                default:
                    lblStatus.Text = "Please specify your relation with the child.";
                    return;
            }

            try
            {
                this.loggedInPerson.ApplyForBirthCertificate(objBirthCertificate, relationWithChild, txtVerificationCode.Text);
            }
            catch (ApplicationException ex)
            {
                lblStatus.Text = ex.Message;
                return;
            }
            catch (Exception ex)
            {
                Logger.ErrorLogger.Log(ex);
                lblStatus.Text = "An unexpected error occured on the application. Please contact the appropriate technical candidate for more information.";
                return;
            }

            lblStatus.Text = "Application sent successfully.";

            EmailHelper.SendApplicationRequestNotification("BirthCertificate", this.loggedInPerson, ref lblStatus);
            SMSHelper.SendApplicationRequestNotification("BirthCertificate", this.loggedInPerson, ref lblStatus);

            pnlBirthCertificateRequest.Visible = false;
            pnlDisplay.Visible = true;
        }

        protected void cblFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.FillBirthCertificateGrid();
        }

        protected void btnViewAll_Click(object sender, EventArgs e)
        {
            gvBirthCertificate.Visible = true;
            pnlFilter.Visible = true;
            pnlTools.Visible = false;
            pnlDisplay.Visible = false;
            pnlAdminActions.Visible = false;

            this.FillBirthCertificateGrid();
        }

        protected void btnViewBirthCertificateRequest_Click(object sender, EventArgs e)
        {
            pnlTools.Visible = false;
            gvBirthCertificate.Visible = true;
            pnlDisplay.Visible = false;
            pnlAdminActions.Visible = false;

            this.FillBirthCertificateGrid();
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            try
            {
                var birthCertificate = ControlledModel.BirthCertificate.FindById(Convert.ToInt32(hdnBirthCertificateId.Value));
                this.loggedInAdmin.ApproveBirthCertificate(birthCertificate);
                lblStatus.Text = "The record is Approved successfully!";

                EmailHelper.SendApproveEmail("BirthCertificate", birthCertificate.Person, ref lblStatus);
                SMSHelper.SendApproveSMS("BirthCertificate", birthCertificate.Person, ref lblStatus);
            }
            catch (ApplicationException ex)
            {
                lblStatus.Text = ex.Message;
                return;
            }
            catch (Exception ex)
            {
                Logger.ErrorLogger.Log(ex);
                lblStatus.Text = "An unexpected error occured on the application. Please contact the appropriate technical candidate for more information.";
            }
            finally
            {
                pnlAdminActions.Visible = false;
            }
        }

        protected void btnDeactivate_Click(object sender, EventArgs e)
        {
            try
            {
                var birthCertificate = ControlledModel.BirthCertificate.FindById(Convert.ToInt32(hdnBirthCertificateId.Value));
                
                if (btnDeactivate.Text == "Re-Activate")
                {
                    this.loggedInAdmin.ReActivateBirthCertificate(birthCertificate);
                    lblStatus.Text = "The record is Re-Activated successfully!";
                }
                else
                {
                    this.loggedInAdmin.DeactivateBirthCertificate(birthCertificate, txtReason.Text);
                    lblStatus.Text = "The record is Deactivated successfully!";
                }

                EmailHelper.SendDeactivationEmail("BirthCertificate", btnDeactivate.Text, birthCertificate.Person, txtReason.Text ,ref lblStatus);
                SMSHelper.SendDeactivationSMS("BirthCertificate", btnDeactivate.Text, birthCertificate.Person, ref lblStatus);
            }
            catch (ApplicationException ex)
            {
                lblStatus.Text = ex.Message;
                return;
            }
            catch (Exception ex)
            {
                Logger.ErrorLogger.Log(ex);
                lblStatus.Text = "An unexpected error occured on the application. Please contact the appropriate technical candidate for more information.";
            }
            finally
            {
                pnlAdminActions.Visible = false;
            }
        }

        protected void btnDeny_Click(object sender, EventArgs e)
        {
            try
            {
                var birthCertificate = ControlledModel.BirthCertificate.FindById(Convert.ToInt32(hdnBirthCertificateId.Value));
                this.loggedInAdmin.DenayBirthCertificate(birthCertificate, txtReason.Text);
                lblStatus.Text = "The record is Denyed successfully!";

                EmailHelper.SendDenyNotificationEmail("BirthCertificate", birthCertificate.Person, txtReason.Text, ref lblStatus);
                SMSHelper.SendDenyNotificationSMS("BirthCertificate", birthCertificate.Person, ref lblStatus);
            }
            catch (ApplicationException ex)
            {
                lblStatus.Text = ex.Message;
                return;
            }
            catch (Exception ex)
            {
                Logger.ErrorLogger.Log(ex);
                lblStatus.Text = "An unexpected error occured on the application. Please contact the appropriate technical candidate for more information.";
            }
            finally
            {
                pnlAdminActions.Visible = false;
            }
        }
    }
}